package com.example.mes_sys.service.impl;

import com.example.mes_sys.dto.LoginRequestDto;
import com.example.mes_sys.jwt.JwtTokenProvider;
import com.example.mes_sys.po.SysUserPo;
import com.example.mes_sys.service.LoginService;
import com.example.mes_sys.vo.UserDetailsVo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
@Transactional
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    private final AuthenticationManager authenticationManager;
    private final JwtTokenProvider jwtTokenProvider;
    @Override
    public UserDetailsVo login(LoginRequestDto loginRequest) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //生成jwt token令牌
        String token = jwtTokenProvider.generateToken(authenticate);
        UserDetailsVo userDetailsVo = (UserDetailsVo) authenticate.getPrincipal();
        userDetailsVo.setToken(token);
        return userDetailsVo;
    }
}
